/**
 * Project Name:BGI_DX
 * File Name:ReflectUtil.java
 * Package Name:com.bgi.dx.common.pulgin
 * Date:2014-10-20下午09:43:08
 * Copyright (c) 2014, BGI_DX All Rights Reserved.
 *
 */

package com.bgi.uims.common.pulgin;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ClassName:ReflectUtil <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2014-10-20 下午09:43:08 <br/>
 * 
 * @author fukun
 * @version
 * @since JDK 1.7
 * @see
 */
public class ReflectUtil {
	private static final Log logger = LogFactory.getLog(ReflectUtil.class);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void setFieldValue(Object target, String fname, Class ftype,
			Object fvalue) {
		if (target == null
				|| fname == null
				|| "".equals(fname)
				|| (fvalue != null && !ftype
						.isAssignableFrom(fvalue.getClass()))) {
			return;
		}
		Class clazz = target.getClass();
		try {
			Method method = clazz.getDeclaredMethod("set"
					+ Character.toUpperCase(fname.charAt(0))
					+ fname.substring(1), ftype);
			if (!Modifier.isPublic(method.getModifiers())) {
				method.setAccessible(true);
			}
			method.invoke(target, fvalue);
		} catch (Exception me) {
			if (logger.isDebugEnabled()) {
				logger.debug(me);
			}
			try {
				Field field = clazz.getDeclaredField(fname);
				if (!Modifier.isPublic(field.getModifiers())) {
					field.setAccessible(true);
				}
				field.set(target, fvalue);
			} catch (Exception fe) {
				if (logger.isDebugEnabled()) {
					logger.debug(fe);
				}
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public static Object getFieldValue(Object target, String fname) {
		Object reslut = null;
		if (target == null || fname == null || "".equals(fname)) {
			return null;
		}
		Class clazz = target.getClass();
		try {
			Field field = clazz.getDeclaredField(fname);
			reslut = field.get(fname);
		} catch (Exception me) {
			if (logger.isDebugEnabled()) {
				logger.debug(me);
			}
		}
		return reslut;
	}
}
